import Request from '@/utils/request';

const flies = import.meta.glob('./modules/*.ts', {
	import: 'default',
	eager: true
});

export default function(this: any, url: String, data = {}, params = {}, axiosHeaders = {}) {
    let urls = (url || "").split("/");
    let fileName = `./modules/${urls.shift()}.ts`;
    console.log(url, urls, flies, fileName);
    let api:any = flies[fileName];
    urls.map(item => {
        api = api[item] || {};
    });
    console.log(api)
    if (this && this.url) {
        api.url = this.url;
    } else if ((this && this.endUrl) || (this&&this.endUrl==0)) {
        api.url = api.url + "/" + this.endUrl;
    }

    const method = (api.method || "").toLowerCase();

    let requestHeaders = {};
    if (api && api.requestHeaders) {
        requestHeaders = api.requestHeaders;
    } else {
        if (new RegExp("post").test(method)) {
            requestHeaders = {
                headers: {
                    "Content-Type": "application/json",
                },
            };
        } else if (new RegExp("put").test(method)) {
            requestHeaders = {
                headers: {
                    "Content-Type": "application/json",
                },
            };
        } else {
            requestHeaders = {};
        }
    }

    if (new RegExp("post").test(method)) {
        return Request({
            url: api.url,
            data: JSON.stringify(data || {}),
            params: params,
            method: api.method,
            ...requestHeaders,
            ...axiosHeaders
        });
    } else {
        return Request({
            url: api.url,
            params: data,
            method: api.method,
            ...requestHeaders,
            ...axiosHeaders
        });
    }
}